import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getConnection } from 'typeorm';
import { SetKey as Entity } from '@/entity/common/set_key/set_key.entity';

@Injectable()
export class SetKeyDao {
  public connection = getConnection();
  constructor(
    @InjectRepository(Entity)
    private readonly repository: Repository<Entity>,
  ) {}

  /**
   * 查询所有
   */
  findAll(params: any): Promise<Entity[]> {
    return this.repository.find({ order: { id: "DESC" } });
  }

  /**
   * 通过type查询所有
   */
  findAllByType(params: any): Promise<Entity[]> {
    return this.repository.find(params);
  }
  
  /**
   * 按条件查询
   */
  findWhere(params: any): Promise<Entity> {
    return this.repository.findOne(params);
  }

  /**
   * 添加
   */
  add(params: any): Promise<Entity> {
    const entity = new Entity();
    Object.assign(entity, params);
    return this.repository.save(entity);
  }

  /**
   * 修改
   * @param params
   */
  async update(params: any): Promise<Entity> {
    const entity = await this.repository.findOne(params.id);
    Object.assign(entity, params);
    return this.repository.save(entity);
  }

  /**
   * 删除
   * @param params
   */
  async delete(params: any): Promise<Entity> {
    const entity = await this.repository.findOne(params.id);
    return this.repository.remove(entity);
  }
}
